package upload

import (
	"MBGAdmin/controllers"
	"MBGAdmin/util"
	"context"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/qiniu/api.v7/v7/auth/qbox"
	"github.com/qiniu/api.v7/v7/storage"
	"path"
	"strconv"
	"time"
)

// 上传控制器
type UploadController struct {
	controllers.BaseController
}

// 上传文件
func (c *UploadController) Post() {
	// 获取文件
	f, h, err := c.GetFile("file")
	if err != nil {
		c.BaseResponse(1, "上传文件出错")
		return
	}
	defer f.Close()

	// 定义七牛上传参数
	var accessKey string = beego.AppConfig.String("qiniuaccessKey")
	var secretKey string = beego.AppConfig.String("qiniusecretKey")
	var scope string = beego.AppConfig.String("qiniuscope")
	var url string = beego.AppConfig.String("qiniuurl")
	var filename string = beego.AppConfig.String("qiniudomain") + "/" +
		strconv.FormatInt(time.Now().Unix(), 10) +
		util.RandString(10) + path.Ext(h.Filename)

	// 设置七牛云参数
	putPolicy := storage.PutPolicy{Scope: scope}
	upToken := putPolicy.UploadToken(qbox.NewMac(accessKey, secretKey))
	formUploader := storage.NewFormUploader(&storage.Config{Zone: &storage.ZoneHuadong})
	ret := storage.PutRet{}
	putExtra := storage.PutExtra{}

	// 提交上传
	err = formUploader.Put(context.Background(), &ret, upToken, filename, f, h.Size, &putExtra)
	if err != nil {
		fmt.Println(err)
		c.BaseResponse(1, "上传文件出错")
		return
	}

	// 响应内容
	response := make(map[string]string)
	response["src"] = url + ret.Key
	c.BaseResponse(0, "上传文件成功", response)
}
